<?php

namespace App\Console\Commands\Wanggui;

use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Models\Common\MapNationalBrandShopModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\Common\ResourcesModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class AddAmapImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:refresh-amap-image {--scope=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新点位图片脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // 根据参数获得刷新图片的区间
        $between = [];

        $scope = $this->option('scope');

        if (strpos($scope, ',') !== false) {
            $scopeArr = explode(',', $scope);
            $between  = [
                Carbon::parse($scopeArr[0])->startOfDay()->timestamp,
                Carbon::parse($scopeArr[1])->endOfDay()->timestamp,
            ];
        }


        if ($scope != 'all') {
            $between = [
                Carbon::now()->subDays(2)->startOfDay()->timestamp,
                Carbon::now()->timestamp
            ];
        }

        // empty(between) ? 刷新所有的 : 刷新一天的

        // 夸父门店
        GuanyuanSyncShopListModel::query()
            ->chunkById(30, function ($shopLists) {
                $wgNumber = collect($shopLists)->map(function ($shop) {
                    return 'KFZC' . str_pad($shop->code, 7, '0', STR_PAD_LEFT);
                })->values()->toArray();
                $res      = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumber)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumber, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }

                // 生成图片
                foreach ($shopLists as $shopList) {
                    $codeNumber = 'KFZC' . str_pad($shopList->code, 7, '0', STR_PAD_LEFT);
                    if (in_array($codeNumber, $diffWgNumber)) {
                        $lng = $shopList->lng;
                        $lat = $shopList->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        $shopList->name = str_replace('）', ')', str_replace('（', '(', $shopList->name));
                        if (mb_strlen($shopList->name) > 15) {
                            $label = mb_substr($shopList->name, 0, 12) . '...';
                        } else {
                            $label = $shopList->name;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;

                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $codeNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $codeNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($codeNumber . '=====>' . $fileArr['path']);

                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });


        // 商场网规
        SiteLocationMallModel::query()
            ->when(!empty($between), function ($query) use ($between) {
                $query->whereBetween('createdAt', $between);
            })->chunkById(30, function ($siteLocationMallLists) {
                $wgNumberList = collect($siteLocationMallLists)->pluck('wgNumber')->toArray();

                $res = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumberList)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumberList, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }
                // 生成图片
                foreach ($siteLocationMallLists as $mall) {
                    if (in_array($mall->wgNumber, $diffWgNumber)) {
                        $lng = $mall->lng;
                        $lat = $mall->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        if (mb_strlen($mall->mallName) > 15) {
                            $label = mb_substr($mall->mallName, 0, 12) . '...';
                        } else {
                            $label = $mall->mallName;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;
                        //
                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $mall->wgNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $mall->wgNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($mall->wgNumber . '=====>' . $fileArr['path']);
                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });

        // 街道
        MapNationalStreetModel::query()
            ->when(!empty($between), function ($query) use ($between) {
                $query->whereBetween('createdAt', $between);
            })->chunkById(30, function ($streetLists) {
                $wgNumberList = collect($streetLists)->pluck('wgNumber')->toArray();

                $res = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumberList)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumberList, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }

                // 生成图片
                foreach ($streetLists as $street) {
                    if (in_array($street->wgNumber, $diffWgNumber)) {
                        $lng = $street->lng;
                        $lat = $street->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        if (mb_strlen($street->name) > 15) {
                            $label = mb_substr($street->name, 0, 12) . '...';
                        } else {
                            $label = $street->name;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;
                        //
                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $street->wgNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $street->wgNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($street->wgNumber . '=====>' . $fileArr['path']);
                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });

        // 高校
        MapNationalUniversitiesModel::query()
            ->when(!empty($between), function ($query) use ($between) {
                $query->whereBetween('createdAt', $between);
            })->chunkById(30, function ($universities) {
                $wgNumberList = collect($universities)->pluck('wgNumber')->toArray();

                $res = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumberList)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumberList, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }

                // 生成图片
                foreach ($universities as $university) {
                    if (in_array($university->wgNumber, $diffWgNumber)) {
                        $lng = $university->lon;
                        $lat = $university->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        if (mb_strlen($university->name) > 15) {
                            $label = mb_substr($university->name, 0, 12) . '...';
                        } else {
                            $label = $university->name;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;
                        //
                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $university->wgNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $university->wgNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($university->wgNumber . '=====>' . $fileArr['path']);
                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });

        // 乡镇
        MapTownshipPlanAreaModel::query()
            ->when(!empty($between), function ($query) use ($between) {
                $query->whereBetween('createdAt', $between);
            })->chunkById(30, function ($townLists) {
                $wgNumberList = collect($townLists)->pluck('wgNumber')->toArray();

                $res = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumberList)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumberList, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }

                // 生成图片
                foreach ($townLists as $town) {
                    if (in_array($town->wgNumber, $diffWgNumber)) {
                        $lng = $town->lng;
                        $lat = $town->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        if (mb_strlen($town->area) > 15) {
                            $label = mb_substr($town->area, 0, 12) . '...';
                        } else {
                            $label = $town->area;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;
                        //
                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $town->wgNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $town->wgNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($town->wgNumber . '=====>' . $fileArr['path']);
                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });

        // 产业园
        MapNationalIndustrialParkModel::query()
            ->when(!empty($between), function ($query) use ($between) {
                $query->whereBetween('createdAt', $between);
            })->chunkById(30, function ($packLists) {
                $wgNumberList = collect($packLists)->pluck('wgNumber')->toArray();

                $res = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumberList)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumberList, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }

                // 生成图片
                foreach ($packLists as $pack) {
                    if (in_array($pack->wgNumber, $diffWgNumber)) {
                        $lng = $pack->lon;
                        $lat = $pack->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        if (mb_strlen($pack->area) > 15) {
                            $label = mb_substr($pack->area, 0, 12) . '...';
                        } else {
                            $label = $pack->area;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;
                        //
                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $pack->wgNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $pack->wgNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($pack->wgNumber . '=====>' . $fileArr['path']);
                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });

        // 品牌
        MapNationalBrandShopModel::query()
            ->when(!empty($between), function ($query) use ($between) {
                $query->whereBetween('createdAt', $between);
            })->chunkById(30, function ($brandLists) {
                $wgNumberList = collect($brandLists)->pluck('wgNumber')->toArray();

                $res = ResourcesModel::query()
                    ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                    ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->where('businessId', 0)
                    ->whereIn('name', $wgNumberList)
                    ->pluck('name')
                    ->toArray();

                // 获得没有图片的 wgNumber
                $diffWgNumber = array_diff($wgNumberList, $res);

                dump($diffWgNumber);

                if (empty($diffWgNumber)) {
                    return null;
                }

                // 生成图片
                foreach ($brandLists as $brand) {
                    if (in_array($brand->wgNumber, $diffWgNumber)) {
                        $lng = $brand->lon;
                        $lat = $brand->lat;
                        if ($lat == 0 || $lng == 0) {
                            continue;
                        }
                        usleep(500000);
                        if (mb_strlen($brand->area) > 15) {
                            $label = mb_substr($brand->area, 0, 12) . '...';
                        } else {
                            $label = $brand->area;
                        }
                        $characters = array(' ', '+', '-', '|', '&', ',');
                        $label      = str_replace($characters, '', $label);
                        $amapUrl    = 'https://restapi.amap.com/v3/staticmap?location=%s,%s&markers=-1,https://file.51kuafu.com/9a/11/8f2998d7c8a1032f6eb1ebf343cd5ba8f8658c237c202c76edbb83578cc9.png,0:%s,%s&zoom=15&size=750*560&labels=%s,3,1,20,0x000000,0xFFF733:%s,%s&key=%s';
                        $key        = WangGuiCityByPower::getRandomAmapKey();
                        $url        = sprintf($amapUrl, $lng, $lat, $lng, $lat, $label, $lng, ($lat + 0.001), $key);
                        // 获取在线文件内容
                        $tempData = (new Client())->request("get", $url)->getBody()->getContents();
                        // 重命名文件
                        $fileName = 'php_import_' . time() . '_' . Str::random(5) . ".png";
                        // 文件存储的路径
                        $savePath = sys_get_temp_dir() . '/' . $fileName;
                        //
                        // 存文件
                        file_put_contents($savePath, $tempData);
                        $fileArr            = FileUtil::uploadFile($savePath);
                        $resource           = ResourcesModel::query()->firstOrNew([
                            'name' => $brand->wgNumber
                        ]);
                        $resource->module   = ResourcesModel::MODULE_TYPE_WG_AUDIT;
                        $resource->business = ResourcesModel::BUSINESS_WG_AUDIT;
                        $resource->name     = $brand->wgNumber;
                        $resource->url      = $fileArr['path'];
                        $resource->isPublic = 1;
                        $resource->save();

                        $this->info($brand->wgNumber . '=====>' . $fileArr['path']);
                        // 删除文件
                        @unlink($savePath);
                    }
                }
            });
    }
}
